//
//  SsehSettingViewController.m
//  customer
//
//  Created by 杨阳 on 2018/10/29.
//  Copyright © 2018 yinlong. All rights reserved.
//

#import "SsehSettingViewController.h"
#import "SsehConfigModel.h"
#import "SsehSettingTableViewCell.h"
#import "LoginViewController.h"
#import "GlobalAddressManagerViewController.h"
#import "FindPasswordViewController.h"
#import "SsehInvoiceTitleViewController.h"
#import "FeedBackViewController.h"
#import "AboutUSViewController.h"

@interface SsehSettingViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * tableView;

@property (nonatomic,strong) NSMutableArray * dataSource;

@property (nonatomic,copy)NSString *sizeString;

@end

static NSString * const SsehSettingTableViewCellID = @"SsehSettingTableViewCellID";

@implementation SsehSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutUI];
}

- (void)layoutUI{
    self.title = @"设置";
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, F_DEVICE_W, F_DEVICE_H-NAVIGATION_BAR_HEIGHT-bottomPadding(100)) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.layer.cornerRadius = 5;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.backgroundColor = [UIColor backGroudColorForView];
    [self.tableView registerNib:[UINib nibWithNibName:@"SsehSettingTableViewCell" bundle:nil] forCellReuseIdentifier:SsehSettingTableViewCellID];
    [self.view addSubview:self.tableView];
    AutoWeakSelf
    UIButton * exitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    exitButton.titleLabel.font = [UIFont systemFontOfSize:16];
    exitButton.layer.cornerRadius = 5;
    exitButton.layer.borderWidth = 1.0f;
    exitButton.layer.borderColor = [UIColor roseRed].CGColor;
    [exitButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [exitButton setBackgroundColor:[UIColor whiteColor]];
    [exitButton setTitleColor:[UIColor roseRed] forState:UIControlStateNormal];
    [exitButton addTarget:self action:@selector(exitApp) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:exitButton];
    [exitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.view).offset(-80);
        make.left.equalTo(weakSelf.view).offset(15);
        make.right.equalTo(weakSelf.view).offset(-15);
        make.height.mas_equalTo(50);
        
    }];
    self.dataSource = [NSMutableArray arrayWithArray:@[@[@"修改登录密码"],@[@"地址管理",@"发票管理",@"意见反馈",@"关于我们"],@[@"清除缓存"]]];
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    self.sizeString = [NSString stringWithFormat:@"%.1fM",[self folderSizeAtPath:cachPath]];
}

- (void)exitApp{
    
    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showLoading];
        NSDictionary * par = @{@"member_id":[NSString emptyStr:K_UserDefault_Read(CustomerUserID)],
                               @"member_token":[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)]
                               };
        [[QYNetManager sharedManager]POST:kOutLogin parameters:par andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
            [self hideLoading];
            if ([responseObject[@"status"] isEqualToString:@"ok"]) {
                [NSString removeUserInfo];
                [self performSelector:@selector(backLoginVC) withObject:nil afterDelay:1.0f];
            }else{
                [self showErrorTipWithTitle:responseObject[@"error"]];
            }
        } Failure:^(NSError *error) {
            [self hideLoading];
            [self showErrorTipWithTitle:CustomerPoolNetStr];
        }];
    }];
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定退出？" preferredStyle:UIAlertControllerStyleAlert];
    [aleVC addAction:act1];
    [aleVC addAction:act2];
    
    [self presentViewController:aleVC animated:YES completion:nil];
    
}

- (void)backLoginVC{
    LoginViewController *login = [[LoginViewController alloc]initWithLoginSuccess:^{
        AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        appDelegate.homeTabBar = [[MainTabBarController alloc]init];
        [appDelegate.window setRootViewController:appDelegate.homeTabBar];
        [appDelegate.window makeKeyAndVisible];
    }];
    AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    UINavigationController * nc = [[UINavigationController alloc]initWithRootViewController:login];
    nc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor]};
    appDelegate.window.rootViewController = nc;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [(NSArray *)self.dataSource[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        FindPasswordViewController *VC = [FindPasswordViewController new];
        VC.isModify = YES;
        TAB_PUSH(self, VC, YES);
    }
    else if (indexPath.section == 1 ){
        if (indexPath.row == 0) {
            GlobalAddressManagerViewController *adsVC = [[GlobalAddressManagerViewController alloc]init];
            adsVC.isSelf = YES;
            TAB_PUSH(self, adsVC, YES);
        }else if (indexPath.row == 1){
            SsehInvoiceTitleViewController *adsVC = [[SsehInvoiceTitleViewController alloc]init];
            TAB_PUSH(self, adsVC, YES);
        }else if (indexPath.row == 2){
            FeedBackViewController *adsVC = [[FeedBackViewController alloc]init];
            TAB_PUSH(self, adsVC, YES);
        }else if (indexPath.row == 3){
            AboutUSViewController *adsVC = [[AboutUSViewController alloc]init];
            TAB_PUSH(self, adsVC, YES);
        }
    }
    else if (indexPath.section == 2){//清除缓存
        UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self myClearCacheAction];
        }];
        UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"清楚缓存？" preferredStyle:UIAlertControllerStyleAlert];
        [aleVC addAction:act1];
        [aleVC addAction:act2];
        [self presentViewController:aleVC animated:YES completion:nil];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SsehSettingTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SsehSettingTableViewCellID];
    cell.titleLabel.text = self.dataSource[indexPath.section][indexPath.row];
    cell.rightImageView.image = [UIImage imageNamed:@"rightshap"];
    if (indexPath.section == 2 && indexPath.row == 0) {
        cell.rightTitleLabel.text = self.sizeString?:@"0.0";
        cell.rightImageView.hidden = YES;
    }else{
        cell.rightTitleLabel.text = @"";
        cell.rightImageView.hidden = NO;
    }
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = [UIColor backGroudColorForView];
    return view;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0001;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = [UIColor backGroudColorForView];
    return view;
    
}

-(void)myClearCacheAction{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
        for (NSString *p in files) {
            NSError *error;
            NSString *path = [cachPath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            //获取尺寸重新加载
            NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            self.sizeString = [NSString stringWithFormat:@"%.1fM",[self folderSizeAtPath:cachPath]];
            [self.tableView reloadData];
        });
    });
}

//遍历文件夹获得文件夹大小，返回多少M
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
- (float )folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
